class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode latter = head, former = null;
        while (latter != null) {
            ListNode node = latter.next;
            latter.next = former;
            former = latter;
            latter = node;
        }
        return former;
    }

    // 使用头指针的next存储链表的下一个需要反转的结点
    public ListNode reverseList2(ListNode head) {
        if (head == null) return null;
        ListNode cur = head;
        while (head.next != null) {
            ListNode temp = cur;
            cur = head.next;
            head.next = cur.next;
            cur.next = temp;
        }
        return cur;
    }

    // 递归
    public ListNode reverseList3(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode ret = reverseList3(head.next);
        head.next.next = head;
        head.next = null;
        return ret;
    }
}
